package com.itmake.sample.dynamic.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.itmake.sample.dynamic.datasource.DynamicDataSource;
import com.itmake.sample.dynamic.enums.DataSourceType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * druid 多数据源配置
 *
 * @author Amjacks
 * @since 2023/08/10
 */
@Configuration
public class DruidFactory {

    private static final Logger log = LoggerFactory.getLogger(DruidFactory.class);

    @Bean
    @ConfigurationProperties("spring.datasource.druid.master")
    @ConditionalOnProperty(prefix = "spring.datasource.druid.master", name = "enabled", havingValue = "true")
    public DataSource masterDataSource(DruidConfig druidConfig) {
        return druidConfig.dataSource(DruidDataSourceBuilder.create().build());
    }

    @Bean
    @ConfigurationProperties("spring.datasource.druid.slave")
    @ConditionalOnProperty(prefix = "spring.datasource.druid.slave", name = "enabled", havingValue = "true")
    public DataSource slaveDataSource(DruidConfig druidConfig) {
        return druidConfig.dataSource(DruidDataSourceBuilder.create().build());
    }

    /**
     *  注册所有数据源
     */
    @Bean(name = "dynamicDataSource")
    @Primary
    public DynamicDataSource dataSource(DataSource masterDataSource) {
        Map<Object, Object> targetDataSources = new HashMap<>();
        // 主数据源
        targetDataSources.put(DataSourceType.MASTER.name(), masterDataSource);
        // 设置数据源
        try {
            // @TODO 获取实例，eg：SpringUtil.getBean("slaveDataSource")
            DataSource slaveDataSource = null;
            targetDataSources.put(DataSourceType.SLAVE.name(), slaveDataSource);
            log.info("成功添加从数据源");
        } catch (Exception ignored) {
            log.warn("未能添加从数据源");
        }
        return new DynamicDataSource(masterDataSource, targetDataSources);
    }
}
